<?php

namespace app\admin\controller;

use app\common\controller\Backend;

class Config extends Backend
{
    public $navTitle = "config";

    public function index()
    {

        $ConfigList = model('Config')->select();

        if ($this->request->isPost()) {
            $formData = $this->request->param();

            $list = model('Config')->column('key,id');

            $ConfigData = [];

            foreach($formData as $key => $item)
            {
                $id = isset($list[$key]) ? $list[$key] : 0;

                $ConfigData[] = [
                    'id' => $id,
                    'value' => $item
                ];
            }

            $idArr = [];

            $files = [];

            if (!empty($_FILES)) {

                foreach ($_FILES as $key => $value) {
                    if ($_FILES[$key]['error'] || $_FILES[$key]['size'] <= 0) continue;

                    $file = upload($key);
                    $files[] = $file;
                    if ($file) {
                        $id = isset($list[$key]) ? $list[$key] : 0;

                        if ($id) {
                            $idArr[] = $id;

                            $ConfigData[] = [
                                'id' => $id,
                                'value' => $file['data'],
                            ];
                        }

                        // @is_file('.' . $ConfigList['avatar']) && unlink('.' . $ConfigList['avatar']);
                    }
                }
            }
            $ConfigThumbs = model('Config')->whereIn('id',$idArr)->select();

            $result = model('Config')->isUpdate()->saveAll($ConfigData);


            if ($result === FALSE) {
                if(!empty($_FILES) && !empty($files))
                {
                    foreach($files as $item)
                    {
                        @is_file('.'.$item['data']) && @unlink('.'.$item['data']);
                    }
                }
                $this->error(model('Config')->getError());
            } else {

                if(!empty($_FILES) && !empty($ConfigThumbs))
                {
                    // halt($ConfigThumbs);
                    foreach($ConfigThumbs as $item)
                    {
                        @is_file('.'.$item['value']) && @unlink('.'.$item['value']);
                    }
                }
                
                $this->success('更新网站配置成功', url('admin/config/index'));
            }
            // halt($ConfigData);



        }

        return $this->fetch('', [
            'navTitle' => $this->navTitle,
            'ConfigList' => $ConfigList
        ]);
    }
}
